/**
 * @file     isHappy.js
 * @brief    [202. 快乐数](https://leetcode.cn/problems/happy-number/)
 * @author   Zhu
 * @date     2022-10-18 22:17
 */

/**
 * Set存储查找是否已出现过
 * @param {number} n
 * @return {boolean}
 */
var isHappy = function (n) {
    const seen = new Set();
    while (!seen.has(n)) {
        if (n === 1) return true;
        seen.add(n);
        n = squareSum(n);
    }
    return false;
};

/**
 * 快慢指针判循环
 * @param {number} n
 * @return {boolean}
 */
var isHappy = function (n) {
    let slow = n,
        fast = n;
    do {
        slow = squareSum(slow);
        fast = squareSum(squareSum(fast));
        if (slow === 1 || fast === 1) return true;
    } while (slow !== fast);
    return false;
};

function squareSum(n) {
    let sum = 0;
    while (n > 0) {
        const g = n % 10;
        sum += g * g;
        n = (n - g) / 10;
    }
    return sum;
}
